// pages/files/fileList.js
Page({
  data: {
    pid: '',
    files: []
  },

  onLoad: function (options) {
    console.log('fileList onLoad', options);
    const pid = options.pid;
    if (!pid) {
      wx.showToast({
        title: '参数错误',
        icon: 'none'
      });
      return;
    }

    this.setData({
      pid
    });

    // 从缓存中获取文件列表
    this.loadFiles(pid);
  },

  // 加载文件列表
  loadFiles: function (pid) {
    try {
      console.log('加载文件列表，pid:', pid);
      const files = wx.getStorageSync(pid);
      console.log('缓存中的文件:', files);

      if (files && Array.isArray(files) && files.length > 0) {
        // 为每个文件添加图标路径
        const filesWithIcons = files.map(file => ({
          ...file,
          iconPath: this.getFileIcon(file.type)
        }));

        this.setData({
          files: filesWithIcons
        });

        // 验证文件是否存在
        this.validateFiles();
      } else {
        console.log('没有找到文件或文件格式不正确');
      }
    } catch (e) {
      console.error('读取缓存失败', e);
      wx.showToast({
        title: '获取文件列表失败',
        icon: 'none'
      });
    }
  },

  // 验证文件是否存在
  validateFiles: function () {
    const fs = wx.getFileSystemManager();
    const validFiles = [];

    for (const file of this.data.files) {
      try {
        fs.accessSync(file.path);
        validFiles.push(file);
      } catch (e) {
        console.log('文件不存在:', file.path);
      }
    }

    if (validFiles.length === 0) {
      this.setData({
        files: []
      });
      wx.removeStorageSync(this.data.pid);
      wx.showToast({
        title: '文件已失效',
        icon: 'none'
      });
    } else if (validFiles.length !== this.data.files.length) {
      this.setData({
        files: validFiles
      });
      wx.setStorageSync(this.data.pid, validFiles);
    }
  },

  // 获取文件图标
  getFileIcon: function (type) {
    console.log('我被调用了')
    // 这个方法在模板中被调用，需要返回图标路径
    const imageTypes = ['jpg', 'jpeg', 'png', 'gif'];
    const docTypes = ['doc', 'docx'];
    const excelTypes = ['xls', 'xlsx'];
    const pptTypes = ['ppt', 'pptx'];
    const pdfType = 'pdf';
    const txtType = 'txt';

    if (imageTypes.includes(type)) return '/assets/icons/image.png';
    if (docTypes.includes(type)) return '/assets/icons/word.png';
    if (excelTypes.includes(type)) return '/assets/icons/excel.png';
    if (pptTypes.includes(type)) return '/assets/icons/ppt.png';
    if (type === pdfType) return '/assets/icons/pdf.png';
    if (type === txtType) return '/assets/icons/txt.png';

    return '/assets/icons/file.png';
  },

  // 跳转到文件详情页
  goToFileDetail: function (e) {
    const index = e.currentTarget.dataset.index;
    const file = this.data.files[index];

    // 检查文件是否存在
    wx.getFileSystemManager().access({
      path: file.path,
      success: () => {
        // 跳转到文件详情页
        wx.navigateTo({
          url: `/pages/files/fileDetail?pid=${this.data.pid}&fileIndex=${index}`
        });
      },
      fail: () => {
        wx.showToast({
          title: '文件已失效',
          icon: 'none'
        });

        // 从列表中移除失效文件
        const newFiles = this.data.files.filter((_, i) => i !== index);
        if (newFiles.length === 0) {
          this.setData({
            files: []
          });
          wx.removeStorageSync(this.data.pid);
        } else {
          this.setData({
            files: newFiles
          });
          wx.setStorageSync(this.data.pid, newFiles);
        }
      }
    });
  },
  onPullDownRefresh() {
    const pid = this.data.pid
    this.loadFiles(pid)
    setTimeout(() => {
      wx.stopPullDownRefresh()
      wx.showToast({
        title: '刷新成功',
        icon: 'success',
        duration: 1000
      })
    }, 1000)
  }
})